<?php

class Client_Table_Accounts extends Apk_Db_Table
{
	protected $_name      = 'accounts';
    protected $_primary   = 'id';

    protected $_referenceMap    = array(
                                        'Role' => array(
                                            'columns'           => 'role_id',
                                            'refTableClass'     => 'Client_Table_Role',
                                            'refColumns'        => 'id'
                                        )
                                    );

    public $_ERROR = '';
    public $_lang = 'ru';

    public function GetError()
    {
    	return $this->_ERROR;
    }

    public function GetCount()
    {
    	return parent::getCount('is_active = 1 and is_removed=0 and is_ghost=0');
    }

    public function GetDataRow($id, $lang = 'ru', $decorator='simple')
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
					->joinLeft('countries', 'countries.id = accounts.id_country', array('country' => 'name_'.$lang))
					->joinLeft('regions', 'regions.id = accounts.id_region', array('region' => 'name_'.$lang))
					->joinLeft('cities', 'cities.id = accounts.id_city', array('city' => 'name_'.$lang))
					->where('accounts.is_active')
					->where('accounts.is_ghost = 0')
					->where('accounts.is_removed = 0')
    				->where('accounts.id = ?', $id);

    	return $this->setDecorator($decorator.'Decorator')->getList($sel)->getRow(0)->toArray();
    }

    public function GetDataList($params = array())
    {
		$sel = $this->getAdapter()->select()
			->from($this->_name, array('id','first_name', 'last_name', 'email', 'phones', 'id_city'))
			->joinLeft('cities', 'cities.id = accounts.id_city', array('city' => 'name_'.$this->_lang))
			->where('accounts.is_active')
			->where('accounts.is_ghost = 0')
			->where('accounts.is_removed = 0');

		if(count($params) > 0)
		foreach($params as $k => $v)
		{
			switch($k)
			{
				case 'search_text':
					if(trim($v) != '')
					$sel->where('accounts.username like \'%'.$v.'%\' or accounts.name like \'%'.$v.'%\' ');
					break;
				default:
					if(!is_null($v) && intval($v) > 0)
					$sel->where('accounts.'.$k.' = ?', $v);
			}
		}

		//echo $sel->assemble(); die();

		return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }

    public function GetDataLast($limit = 6)
    {
		$sel = $this->getAdapter()->select()
			->from($this->_name)
			->where('accounts.is_active')
			->where('accounts.is_ghost = 0')
			->where('accounts.is_removed = 0')
			->where('accounts.is_registrated = 1')
			->order('accounts.add_date desc')
			->limit($limit);

		return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }

    public function GetContacts()
    {
		$sel = $this->getAdapter()->select()
			->from('accounts_cats_rel')
			->join('accounts', 'accounts.id = accounts_cats_rel.id_acc', array())
			->join('categories', 'categories.id = accounts_cats_rel.id_cat', array('parent_id', 'menu_name' => 'menu_name_ru', 'path', 'file_name', 'url'))
			->where('accounts.is_ghost = 0')
			->where('accounts.is_removed = 0')
			->where('accounts.is_active = 1')
			->where('accounts.role_id = 14')
			->group('accounts_cats_rel.id_cat');

		return  $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }

    public function GetContactsUsers()
    {
		$sel = $this->getAdapter()->select()
			->from('accounts_cats_rel')
			->join('accounts', 'accounts.id = accounts_cats_rel.id_acc', array('id','first_name', 'last_name', 'email', 'phones', 'id_city'))
			->join('categories', 'categories.id = accounts_cats_rel.id_cat', array())
			->where('accounts.is_ghost = 0')
			->where('accounts.is_removed = 0')
			->where('accounts.is_active = 1')
			->where('accounts.role_id = 14');

		return  $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }


    public function CheckAccount($id)
    {
    	 $sel = $this->getAdapter()->select()
    	 				->from($this->_name)
    	 				->where('id = ?', $id);

		$data = $this->getList($sel)->toArray();

		if(count($data) == 0) return false;

		if($data[0]['is_removed'] == 1 || $data[0]['is_ghost'] == 1 || $data[0]['is_active'] == 0) return false;

		return true;
    }

    //************************************************/
    // Updating data info
	//************************************************/

	public function insert(array $data, $user_id)
    {
        $data['add_date'] = time();
        $data['modify_date'] = time();
        $data['birth_date'] = time();

        $data['add_user_id'] = $user_id;
        $data['modify_user_id'] = $user_id;

    	return parent::insert($data);
    }

    public function update($data, $id, $user_id)
    {
    	$this->getAdapter()->delete('accounts_phones', 'id_acc = '.$id);
    	foreach ($data['phones'] as $k => $phone)
    	{
    		if(trim($phone) != '')
    		{
	    		$p['id_acc'] = $id;
	    		$p['phone'] = $phone;
	    		$p['id_phone_type'] = $data['types'][$k];
	    		$this->getAdapter()->insert('accounts_phones', $p);
    		}
    	}

    	//if($data['pass1'] != '')
			//if(!($data['password']  = $this->check_password($data['pass1'], $data['pass2']))) return false;

    	$data['modify_user_id'] = $user_id;
    	$data['modify_date'] = time();

    	unset($data['phones']);
    	unset($data['types']);
		unset($data['pass1']);
		unset($data['pass2']);

		return parent::update($data, 'id = '.$id);
    }

    public function remove($items, $user_id)
    {
    	foreach($items as $k => $id)
    	{
	    	$data['modify_user_id'] = $user_id;
	    	$data['modify_date'] = time();
	    	$data['is_removed'] = 1;

	    	parent::update($data, 'id = '.$id);
    	}

    	return true;
	}

	public function LastVisitDateUpdate($id)
    {
	   $data['lastvisit_date'] = time();
	   parent::update($data, 'id = '.$id);
	}

	public function offline($id)
    {
	   $data['lastvisit_date'] = 0;
	   parent::update($data, 'id = '.$id);
	}

	public function add_friend(array $data)
    {
    	try{
    	    $this->getAdapter()->insert('accounts_friends', $data);
    	}catch (Exception $e){}
    }

	public function remove_friend($data)
    {
    	try{
    	    $this->getAdapter()->delete('accounts_friends', 'id_account = '.$data['id_account'].' and id_friend = '.$data['id_friend']);
    	}catch (Exception $e){}
    }

	public function accept_friend($data)
    {
    	try{
    	    $this->getAdapter()->update('accounts_friends', array('is_accept' => 1),
    	    							'id_account = '.$data['id_account'].' and id_friend = '.$data['id_friend']);
    	}catch (Exception $e){}
    }

	public function notaccept_friend($data)
    {
    	try{
    	    $this->getAdapter()->delete('accounts_friends',
    	    							'id_account = '.$data['id_account'].' and id_friend = '.$data['id_friend']);
    	}catch (Exception $e){}
    }

    public function pre_register($data)
    {

    	if(!($data['email'] = $this->check_email($data['email'])))
    		return false;

    	$arr = explode('@', $data['email']);
    	if(!($data['username'] = $this->check_login($arr[0].time())))
    		return false;

    	if(!($data['password'] = $this->check_password($data['pass1'], $data['pass2'])))
    		return false;

    	unset($data['pass1']);
    	unset($data['pass2']);

    	$data['activation_code'] = md5($data['email'].time());
    	$data['is_registrated'] = 0;
    	$data['add_date'] = time();
    	$data['modify_date'] = time();

    	try{
    	    $this->getAdapter()->insert('accounts', $data);
    	}catch (Exception $e){
    		$this->_ERROR = $e->__toString();
    		return false;
    	}

    	$this->SendPreRegMail($data);

    	return true;
    }

    public function register($data, $id)
    {
    	 if(!($data['username'] = $this->check_login($data['username'])))
    	 	return false;

    	 if(strlen($data['name']) < 4)
    	 {
    	 	$this->_ERROR = 'Пожалуйста, укажите сове Имя';
    	 	return false;
    	 }

    	 if(strlen($data['surname']) < 4)
    	 {
    	 	$this->_ERROR = 'Пожалуйста, укажите свою Фамилию';
    	 	return false;
    	 }

    	 if(!isset($data['agreeWithTerms'])
    	 || !isset($data['agreeWithRules'])
    	 || !isset($data['agreeWithRules1'])
    	 || !isset($data['agreeWithRules2'])
    	 || !isset($data['agreeWithRules3'])){
    	 	$this->_ERROR = 'Вы не согласны с пользовательским соглашением';
    	 	return false;
    	 }

    	 unset($data['agreeWithTerms']);
    	 unset($data['agreeWithRules']);
    	 unset($data['agreeWithRules1']);
    	 unset($data['agreeWithRules2']);
    	 unset($data['agreeWithRules3']);
    	 unset($data['code']);

    	 $data['is_registrated'] = 1;
    	 $data['modify_date'] = time();

    	 //print_r($data); die();

    	 return parent::update($data, 'id = '.$id);
    }


    public function activate($code)
    {
		if(trim($code) == '')
		{
			$this->_ERROR = 'Пожалуйста введи код активации';
			return false;
		}

    	$sel = $this->select()->from($this->_name)
				->where('activation_code = ?', $code);
		$data = $this->getList($sel)->toArray();

		if(count($data) == 0)
		{
			$this->_ERROR = 'Пользователь не найден либо уже активирован';
			return false;
		}

		$d['activation_code'] = 'OK';
		$d['is_active'] = true;
		$d['is_ghost'] = false;

		parent::update($d, 'id = '.$data[0]['id']);

		return $data[0];
    }


    //************************************************/
    // Checking data functions
	//************************************************/


    public function check_user($email)
    {
		$sel = $this->select()->from($this->_name)
				->where('email = ?', $email);

		$data = $this->getList($sel)->toArray();

		if(count($data) == 0) return true;

		if($data[0]['activation_code'] != 'OK')
		{
			$this->_ERROR = 'Пожалуйста, сначала активируйте вашу учетную запись';
			return false;
		}

		if($data[0]['is_active'] != 1)
		{
			$this->_ERROR = 'Пожалуйста, обратитесь к администратору, ваша учетная запись блокирована';
			return false;
		}

		return true;
    }

    public function check_login($val)
    {
		$val = strtolower(trim($val));

        if($val == '' || strlen($val) < 3){
        	$this->_ERROR = 'Недопустимый Логин';
        	return false;
        }

        $vald = new Zend_Validate_Regex('/^[a-zA-Z0-9_.*а-яА-Я$@%-]*$/u');

        if(!$vald->isValid($val))
        {
           $this->_ERROR = 'Недопустимый Логин';
           return false;
        }

		$sel = $this->select()->from($this->_name)
				->where('username = ?', $val);
		$data = $this->getAdapter()->fetchAll($sel);
		if(count($data) > 0)
		{
			$this->_ERROR = 'Такой Логин уже существует.';
			return false;
		}
		return $val;
    }

    public function check_email($val)
    {
		$val = trim($val);
        if($val == ''){
        	$this->_ERROR = 'Необходимо ввести E-mail';
        	return false;
        }

    	$vald_email = new Zend_Validate_EmailAddress();
        if(!$vald_email->isValid($val))
        {
           $this->_ERROR = implode(',', $vald_email->getMessages());
           return false;
        }
		$sel = $this->getAdapter()->select()->from($this->_name)->where('email = ?', $val);
		$data = $this->getAdapter()->fetchAll($sel);
		if(count($data) > 0)
		{
			$this->_ERROR = 'Пользователь с таким E-mail уже существует.';
			return false;
		}

		return $val;
    }

    public function check_password($pass1, $pass2)
    {
        if($pass1 == ''){
        	$this->_ERROR = 'Необходимо ввести пароль';
        	return false;
        }

        if($pass2 == ''){
        	$this->_ERROR = 'Необходимо подтвердить пароль';
        	return false;
        }

        if($pass1 != $pass2){
        	$this->_ERROR = 'Неверное подтверждение пароля';
        	return false;
        }

        return sha1(md5($pass1));
    }



    //************************************************/
    //  Mailing
    //************************************************/

	public function SendPreRegMail($data)
	{
    	$mail = new Zend_Mail("Windows-1251");

    	$text = '<h1>Добро пожаловать на сайт компании Mitsubishi Ukrainian!</h1>';
    	$text .= '<p>Для активации Вашей учетной записи зайдите пожалуйста по ссылке: <a href="http://community.masik.in.ua/auth/activation">http://community.masik.in.ua/auth/activation</a> <br/>';
    	$text .= 'и введите в форму код активации.</p>';
    	$text .= '<p>Ваш код активации: '.$data['activation_code'].'</p>';

    	$mail->setBodyHtml(iconv("UTF-8", "Windows-1251", $text), 'Windows-1251');

    	$mail->setFrom('info@masik.in.ua', 'masik.in.ua');
    	$mail->addTo($data['email']);
    	$mail->setSubject(iconv("UTF-8", "Windows-1251", '[Mitsubishi Ukrainian] - Активация вашей учетной записи'));
    	$mail->send();
	}


    //************************************************/
    //  Decorators
    //************************************************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'add_date':
            case 'modify_date':
            case 'birth_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            case 'lastvisit_date':
            	$curr_date = getdate();
            	$online = mktime ($curr_date['hours'],$curr_date['minutes']-5, $curr_date['seconds'],
            					  $curr_date['mon'],$curr_date['mday'], $curr_date['year']);

            	if($online > $value) $result['online'] = 'Offline';
            	else $result['online'] = 'Online';

            	break;

            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

    public function viewDecorator($key, $value)
    {
        switch ($key) {
            case 'add_date':
            case 'modify_date':
            case 'birth_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;

            case 'gender':
            	$val = intval($value);
            	$arr = Zend_Registry::get('config')->gender->row->toArray();

            	$result[$key] = 0;

            	foreach($arr as $k => $item)
            		if($item['id'] == $val) $result[$key] = $item['name'];

            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

}
?>